var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
var fs = require('fs');
var moment = require('moment');
var path = require("path");
var db = require('./../../utils/db.js');
/**
 * 上传 控制器
 */
var uploadPath = "D:\\Develop\\phpStudy\\WWW\\FileRes\\allinone\\";
router.post('/uploadFile', function (req, res, next) {
    //判断路径是否存在
    fs.exists(uploadPath, function (exists) {
        if (!exists) {
            mkdirs(uploadPath);
        }
        /* 生成multiparty对象，并配置上传目标路径 */
        var form = new multiparty.Form();
        /* 设置编辑 */
        form.encoding = 'utf-8';
        //设置文件存储路劲
        form.uploadDir = uploadPath;
        //设置文件大小限制
        form.maxFilesSize = 2 * 1024 * 1024;
        // form.maxFields = 1000;   //设置所有文件的大小总和
        //上传后处理
        form.parse(req, function (err, fields, files) {
            var filesTemp = JSON.stringify(files, null, 2);
            if (err) {
                console.log('parse error:' + err);
            } else {
                var momentDate = moment(new Date());
                var createTime = momentDate.format('YYYY-MM-DD HH:mm:ss');
                var createDate = momentDate.format('YYYY-MM-DD');
                var createById = req.session.loginedUser ? req.session.loginedUser.id : null;
                console.log('parse files:' + filesTemp);
                var inputFile = files.file[0];
                var fileSize = inputFile.size;
                var uploadedPath = inputFile.path;

                var fileName = inputFile.originalFilename;
                var fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                var newFileName = momentDate.format('YYYYMMDDHHmmss') + Math.round(Math.random() * 1000) + "." + fileSuffix;
                var dstPath = uploadPath + newFileName;
                //重命名为真实文件名
                fs.rename(uploadedPath, dstPath, function (err) {
                    if (err) {
                        console.log('rename error:' + err);
                    } else {
                        console.log('rename ok');
                    }
                });
                var sql = 'insert into upload(original_name,file_path,size,suffix,create_time,create_date,create_by_id,remark) values' +
                    '("' + fileName + '","' + newFileName + '","' + fileSize + '","' + fileSuffix + '","' + createTime + '","' + createDate + '",' + createById + ',"")';
                db.query(sql, function (err, rows) {
                    if (err) {
                        console.log("新增失败")
                    } else {
                        var file = {
                            'id': rows.insertId,
                            'fileName': fileName,
                            'newFileName': newFileName,
                            'path': dstPath,
                            'fileSize': fileSize,
                            'fileSuffix': fileSuffix,
                            'createTime': createTime,
                            'createDate': createDate,
                            'createById': createById
                        };
                        res.json({
                            message: '文件上传成功',
                            errcode: 0,
                            data: file
                        });
                    }
                });
            }

        })
    });
});

//显示所有文件
router.get('/files', function (req, res, next) {
    var uploadIdStr = req.query["uploadIdStr"];
    if (uploadIdStr) {
        var selectUploadSql = "SELECT * FROM upload WHERE id IN (" + uploadIdStr + ")";
        db.query(selectUploadSql, function (err, rows) {
            if (err) {
                console.log("查询失败")
            } else {
                var files = [];
                for (var i = 0; i < rows.length; i++) {
                    var file = {
                        'id': rows[i].id,
                        'original_name': rows[i].original_name
                    };
                    files.push(file)
                }
                res.json({
                    message: '文件查询成功',
                    errcode: 0,
                    data: files
                });
            }
        });
    }
});


//文件下载
router.get('/downloadFile/:id', function(req, res, next) {
    // 实现文件下载
    var fileId = req.params.id;
    var selectUploadSql = "SELECT * FROM upload WHERE id = " + fileId;
    db.query(selectUploadSql, function (err, rows) {
        if (err) {
            console.log("查询失败")
        } else {
            var fileName = rows[0].file_path;
            var oldfileName = rows[0].original_name;
            var filePath = uploadPath + fileName;
            res.download(filePath, oldfileName);
        }
    });
});


//文件删除
router.get('/deleteFile/:id', function (req, res, next) {
    var fileId = req.params.id;
    var selectUploadSql = "SELECT * FROM upload WHERE id = "+ fileId;
    var deleteUploadSql = "delete from upload where id = "+ fileId;
    db.query(selectUploadSql, function (err, rows) {
        if (err) {
            console.log("删除失败");
            res.json({
                message: '删除失败',
                errcode: 1
            });
        } else {
            var fileName = rows[0].file_path;
            var filePath = uploadPath + fileName;
            fs.unlink(filePath,function (a) {
                db.query(deleteUploadSql, function (err, rows) {
                    if (err) {
                        console.log("删除失败");
                        res.json({
                            message: '删除失败',
                            errcode: 1
                        });
                    }else {
                        console.log("删除成功");
                        res.json({
                            message: '删除成功',
                            errcode: 0
                        });
                    }
                })
            });
        }
    });

});

//客户反馈用显示所有文件
router.post('/feedBackFiles', function (req, res, next) {
    var uploadIdStr = req.body["uploadIdStr"];
    if (uploadIdStr) {
        var selectUploadSql = "SELECT * FROM upload WHERE id IN (" + uploadIdStr + ")";
        db.query(selectUploadSql, function (err, rows) {
            if (err) {
                console.log("查询失败")
            } else {
                var files = [];
                for (var i = 0; i < rows.length; i++) {
                    var file = {
                        'id': rows[i].id,
                        'original_name': rows[i].original_name
                    };
                    files.push(file)
                }
                res.json({
                    message: '文件查询成功',
                    errcode: 0,
                    data: files
                });
            }
        });
    }
});


//客户反馈用显示所有文件
router.post('/allFiles', function (req, res, next) {
    var selectUploadSql = "SELECT * FROM upload WHERE 1=1";
    db.query(selectUploadSql, function (err, rows) {
        if (err) {
            console.log("查询失败")
        } else {
            var files = [];
            for (var i = 0; i < rows.length; i++) {
                var file = {
                    'id': rows[i].id,
                    'original_name': rows[i].original_name
                };
                files.push(file)
            }
            res.json({
                message: '文件查询成功',
                errcode: 0,
                data: files
            });
        }
    });
});

//创建文件夹
function mkdir(pos, dirArray, _callback) {
    var len = dirArray.length;
    if (pos >= len || pos > 10) {
        _callback();
        return;
    }
    var currentDir = '';
    for (var i = 0; i <= pos; i++) {
        if (i != 0) currentDir += '/';
        currentDir += dirArray[i];
    }
    fs.exists(currentDir, function (exists) {
        if (!exists) {
            fs.mkdir(currentDir, function (err) {
                if (err) {
                    console.log('创建文件夹出错！');
                } else {
                    console.log(currentDir + '文件夹-创建成功！');
                    mkdir(pos + 1, dirArray, _callback);
                }
            });
        } else {
            console.log(currentDir + '文件夹-已存在！');
            mkdir(pos + 1, dirArray, _callback);
        }
    });
}

//创建目录结构
function mkdirs(dirpath) {
    var dirArray = dirpath.split('/');
    fs.exists(dirpath, function (exists) {
        if (!exists) {
            mkdir(0, dirArray, function () {
                console.log('文件夹创建完毕!准备写入文件!');
            });
        } else {
            console.log('文件夹已经存在!准备写入文件!');
        }
    });
    return true
}

module.exports = router;